<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import {
  getStationsApi,
  addStationApi,
  deleteStationsApi,
  updateStationApi,
  downloadStationTemplateApi
} from '@/api/role'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/SiteWrite.vue'
import Detail from './components/SiteDetail.vue'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import { ElTree, ElInput, ElDivider, ElTag, ElUpload, ElIcon, ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'
import { Plus } from '@element-plus/icons-vue'
const PATH_URL = import.meta.env.VITE_API_BASE_PATH
import { useUserStoreWithOut } from '@/store/modules/user'
const userStore = useUserStoreWithOut()
const uploadUrl = PATH_URL + 'api/CollectionStation/ExportStations'
const headers = ref({ Authorization: userStore.getToken ?? '' })
const { t } = useI18n()
const ids = ref<string[]>([])
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getStationsApi({
      pageNo: unref(currentPage),
      pageRow: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.pageModels || [],
      total: res.data.totalCount
    }
  },
  fetchDelApi: async () => {
    const res = await deleteStationsApi(unref(ids))
    return !!res
  }
})

const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },
  {
    field: 'stationNo',
    label: t('site.stationNo')
  },
  {
    field: 'stationName',
    label: t('site.stationName')
  },
  // {
  //   field: 'stationProtocol',
  //   label: t('site.stationProtocol')
  // },
  // {
  //   field: 'stationIp',
  //   label: t('site.stationIp')
  // },
  // {
  //   field: 'stationPort',
  //   label: t('site.stationPort')
  // },
  {
    field: 'stationKey',
    label: t('site.stationKey')
  },
  {
    field: 'stationAdmin',
    label: t('site.stationAdmin')
  },
  {
    field: 'stationPhone',
    label: t('site.stationPhone')
  },
  {
    field: 'remark',
    label: t('common.remark')
  },
  // {
  //   field: 'isOnline',
  //   label: t('menu.status'),
  //   slots: {
  //     default: (data: any) => {
  //       return (
  //         <>
  //           <ElTag type={data.row.isOnline === 1 ? 'success' : 'danger'}>
  //             {data.row.isOnline === 1 ? t('site.online') : t('site.unLine')}
  //           </ElTag>
  //         </>
  //       )
  //     }
  //   }
  // },
  // {
  //   field: 'isEnabled',
  //   label: t('menu.status'),
  //   slots: {
  //     default: (data: any) => {
  //       return (
  //         <>
  //           <ElTag type={data.row.isEnabled === 1 ? 'success' : 'danger'}>
  //             {data.row.isEnabled === 1 ? t('userDemo.enable') : t('userDemo.disable')}
  //           </ElTag>
  //         </>
  //       )
  //     }
  //   }
  // },
  {
    field: 'createTime',
    label: t('tableDemo.displayTime')
  },

  {
    field: 'action',
    label: t('userDemo.action'),
    width: 260,
    align: 'center',
    fixed: 'right',
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton type="primary" onClick={() => action(row, 'edit')}>
              {t('exampleDemo.edit')}
            </BaseButton>
            <BaseButton type="success" onClick={() => action(row, 'detail')}>
              {t('exampleDemo.detail')}
            </BaseButton>
            <BaseButton type="danger" onClick={() => delData(data.row)}>
              {t('exampleDemo.del')}
            </BaseButton>
          </>
        )
      }
    }
  }
])
const delLoading = ref(false)
const delData = async (row) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row
    ? [row.stationKey]
    : elTableExpose?.getSelectionRows().map((v) => v.stationKey) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const searchSchema = reactive<FormSchema[]>([
  {
    field: 'pageModel.stationNo',
    label: t('site.stationNo'),
    component: 'Input'
  },
  {
    field: 'pageModel.stationName',
    label: t('site.stationName'),
    component: 'Input'
  },
  {
    field: 'pageModel.stationAdmin',
    label: t('site.stationAdmin'),
    component: 'Input'
  }
])

const searchParams = ref({})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const action = (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    // setTimeout(() => {
    //   saveLoading.value = false
    //   dialogVisible.value = false
    // }, 1000)
    let res
    if (actionType.value == 'edit') {
      res = await updateStationApi(formData).finally(() => {
        saveLoading.value = false
      })
    } else {
      res = await addStationApi(formData).finally(() => {
        saveLoading.value = false
      })
    }

    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
const showExport = ref(false)
const successFile = (e) => {
  console.log('successFile-------', e)
  if (e.code == 0) {
    ElMessage.success('导入成功')
    showExport.value = false
    getList()
  } else {
    ElMessage.error(e.msg || '导入失败')
  }
}
const downExcel = async () => {
  const res = await downloadStationTemplateApi()
  if (res) {
    const excelFile = new Blob([res.data], {
      type: 'application/vnd.ms-excel'
    })

    // const url = URL.createObjectURL(excelFile)
    const url = window.URL.createObjectURL(excelFile)
    const a: HTMLAnchorElement = document.createElement('a')
    // 设置<a>元素的属性
    a.href = url
    a.download = '采集站模板.xlsx'
    // 将<a>元素添加到文档中
    document.body.appendChild(a)
    // 触发点击事件
    a.click()
    URL.revokeObjectURL(a.href)
    // 移除<a>元素
    document.body.removeChild(a)
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
      <BaseButton type="primary" @click="showExport = true">{{
        t('exampleDemo.import')
      }}</BaseButton>
      <!-- <BaseButton type="primary" @click="exportToExcel">{{ t('exampleDemo.exprot') }}</BaseButton> -->
      <BaseButton type="primary" @click="downExcel">下载模板</BaseButton>
    </div>
    <Table
      :columns="tableColumns"
      default-expand-all
      node-key="id"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow" />
    <Detail v-else :current-row="currentRow" />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
  <Dialog v-model="showExport" title="导入模板">
    <div class="uploaddiv">
      <!--  :action="uploadUrl" -->
      <ElUpload
        accept=".xlsx, .xls"
        drag
        action="/api/CollectionStation/ExportStations"
        :headers="headers"
        :on-success="successFile"
      >
        <el-icon class="el-icon--upload"><Plus /></el-icon>
        <div class="el-upload__text">点击或拖拽文件到此处上传</div>
        <div class="el-upload__text">支持.xlsx, .xls</div>
      </ElUpload>
    </div>
    <template #footer>
      <BaseButton @click="showExport = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
